package myschool.filter;

import myschool.entity.Admin;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.util.*;

/**
 * @author oldliu
 * @since 1.0
 */

@WebListener
public class MySchoolSessionListener implements HttpSessionAttributeListener {
    public static List<String> useronline = new ArrayList<>();

    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        System.out.println("session id:" + httpSessionBindingEvent.getSession().getId());
        System.out.println(httpSessionBindingEvent.getName() + "=" + httpSessionBindingEvent.getValue() +
                ">>>加入了session");

        if (httpSessionBindingEvent.getName().equals("USER_LOGIN")) {
            Admin admin = (Admin) httpSessionBindingEvent.getValue();
            if (!useronline.contains(admin.getUsername())) {
                useronline.add(admin.getUsername());
            }
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
        System.out.println("session id:" + httpSessionBindingEvent.getSession().getId());
        System.out.println(httpSessionBindingEvent.getName() + "=" + httpSessionBindingEvent.getValue() +
                ">>>从session删除了");

        if (httpSessionBindingEvent.getName().equals("USER_LOGIN")) {
            Admin admin = (Admin) httpSessionBindingEvent.getValue();
            useronline.remove(admin.getUsername());
        }

    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
        System.out.println("session id:" + httpSessionBindingEvent.getSession().getId());
        System.out.println(httpSessionBindingEvent.getName() + "=" + httpSessionBindingEvent.getValue() + ">>>session 替换了");

    }
}
